package com.jw.qme.socket.task;

import com.jw.qme.service.impl.HeartbeatService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Map;

/**
 * ClassName: com.jw.qme.socket
 * Datetime: 2025/4/5 下午6:23
 * Description:
 *
 * @author 汪佳泉
 * @version 1.0
 * @since 1.0
 */
@Component
@RequiredArgsConstructor
public class SocketChannelRemoveTask {

    private final Map<String, SocketChannel> socketChannels;

    private final HeartbeatService heartbeatService;

    // 每5秒执行一次
    @Scheduled(fixedRate = 5000)
    public void removeClosedChannels() {
        Iterator<Map.Entry<String, SocketChannel>> iterator = socketChannels.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, SocketChannel> entry = iterator.next();
            SocketChannel channel = entry.getValue();
            try {
                if (channel == null || !channel.isOpen() || !channel.isConnected() || heartbeatService.getUserStatus(entry.getKey()).isSuccess() ) {
                    System.out.println("清理失效连接: " + entry.getKey());
                    iterator.remove();
                }
            } catch (Exception e) {
                System.err.println("清理连接失败: " + entry.getKey());
                iterator.remove();
            }
        }
    }


}
